﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;

namespace Enter.Common
{
   public class FileHelper
    {
        public static string Combine(string path1, string path2)
        {
            return Path.Combine(path1, path2);
        }

        public static bool Copy(string cfile, string tfile)
        {
            try
            {
                if (IsFile(cfile))
                {
                    File.Copy(cfile, tfile);
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static void CreatedFolder(string files)
        {
            if (!IsFolder(files))
            {
                try
                {
                    Directory.CreateDirectory(files);
                }
                catch
                {
                }
            }
        }

        public static string CreatedFolderData(string Folder)
        {
            string date = DateTime.Now.ToString("yyyyMM");
            return CreatedFolderData(Folder, date);
        }

        public static string CreatedFolderData(string Folder, string date)
        {
            string folderData = string.Empty;
            return CreatedFolderData(Folder, date, out folderData);
        }

        public static string CreatedFolderData(string Folder, out string FolderData)
        {
            string date = DateTime.Now.ToString("yyyyMM");
            return CreatedFolderData(Folder, date, out FolderData);
        }

        public static string CreatedFolderData(string Folder, string date, out string FolderData)
        {
            string files = string.Empty;
            CreatedFolder(Folder);
            FolderData = date + "/";
            files = Folder + FolderData;
            CreatedFolder(files);
            return files;
        }

        public static void DelFile(string file)
        {
            if (IsFile(file))
            {
                try
                {
                    FileInfo info = new FileInfo(file);
                    if (info.Attributes.ToString().IndexOf("ReadOnly") != -1)
                    {
                        info.Attributes = FileAttributes.Normal;
                    }
                    File.Delete(file);
                }
                catch
                {
                }
            }
        }

        public static string[] File_List(string files)
        {
            return Directory.GetFiles(files);
        }

        public static string[] Folder_List(string files)
        {
            return Directory.GetDirectories(files);
        }

        public static string GetExtension(string Files)
        {
            return Path.GetExtension(Files);
        }

        public static string GetFileMapPath(string file)
        {
            HttpContext current = HttpContext.Current;
            string files = string.Empty;
            if (current != null)
            {
                files = current.Server.MapPath(file);
                if (!IsFile(files))
                {
                    files = current.Server.MapPath("/" + file);
                }
                return files;
            }
            return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, file);
        }

        public static string GetFileNameoutExtension(string files)
        {
            if (files.LastIndexOf(".") > 0)
            {
                return files.Substring(0, files.LastIndexOf("."));
            }
            return files;
        }

        public static string GetFileNameWithoutExtension(string files)
        {
            return Path.GetFileNameWithoutExtension(files);
        }

        public static string GetFolderMapPath(string file)
        {
            HttpContext current = HttpContext.Current;
            string files = string.Empty;
            if (current != null)
            {
                files = current.Server.MapPath(file);
                if (!IsFolder(files))
                {
                    files = current.Server.MapPath("/" + file);
                }
                return files;
            }
            return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, file);
        }

        public static string GetFolderName(string Files)
        {
            return Path.GetDirectoryName(Files);
        }

        public static bool IsFile(string files)
        {
            if (!((files.Length != 0) && File.Exists(files)))
            {
                return false;
            }
            return true;
        }

        public static bool IsFolder(string files)
        {
            if (!((files.Length != 0) && Directory.Exists(files)))
            {
                return false;
            }
            return true;
        }

        public static bool IsMap(string Files)
        {
            Files = Files.Replace("//", ":");
            return (Files.IndexOf(':') > 0);
        }

        public static bool IsNum(string str)
        {
            for (int i = 0; i < str.Length; i++)
            {
                if ((str[i] < '0') || (str[i] > '9'))
                {
                    return false;
                }
            }
            return true;
        }
        /// <summary>
        /// 写入日志文件，文件目录按yyyyMM/dd组成
        /// </summary>
        /// <param name="filePath">文件的最顶目录</param>
        /// <param name="fileType"></param>
        /// <param name="content"></param>
        public static void WriteLogFile(string filePath, string fileType, string content)
        {
            try
            {
                string fileFullPath = string.Format("{0}\\{1:yyyyMM}\\{2:dd}\\{3}_{4:yyyyMMdd}.log", filePath, DateTime.Now, DateTime.Now, fileType, DateTime.Now);
                FileInfo file = new FileInfo(fileFullPath);
                if (!Directory.Exists(file.DirectoryName))
                {
                    Directory.CreateDirectory(file.DirectoryName);
                }

                if (file.Length > 1)
                {

                }
                StreamWriter sw = new StreamWriter(fileFullPath, true, System.Text.Encoding.GetEncoding("GB2312"));
                sw.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "]		" + content);
                sw.Close();
            }
            catch { }
        }

        /// <summary>
        /// 写入日志文件，文件目录按yyyyMM/dd组成，默认从配置文件的logfile读取
        /// </summary>
        /// <param name="fileType"></param>
        /// <param name="content"></param>
        public static void WriteLogFile(string fileType, string content)
        {
            try
            {
                string filePath = System.Configuration.ConfigurationManager.AppSettings["logfile"];
                string fileFullPath = string.Format("{0}\\{1:yyyyMM}\\{2:dd}\\{3}_{4:yyyyMMdd}.log", filePath, DateTime.Now, DateTime.Now, fileType, DateTime.Now);
                FileInfo file = new FileInfo(fileFullPath);
                if (!Directory.Exists(file.DirectoryName))
                {
                    Directory.CreateDirectory(file.DirectoryName);
                }

                StreamWriter sw = new StreamWriter(fileFullPath, true, System.Text.Encoding.GetEncoding("GB2312"));
                sw.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "]		" + content);
                sw.Close();
            }
            catch { }
        }

        public static void WriteLogFile(int maxfilelen, string fileType, string content)
        {
            string filePath = System.Configuration.ConfigurationManager.AppSettings["logfile"];
            string fileFullPath = string.Format("{0}\\{1:yyyyMM}\\{2:dd}\\{3}_{4:yyyyMMdd}_1.log", filePath, DateTime.Now, DateTime.Now, fileType, DateTime.Now);
            string newfileFullPath = GetfileFullPath(maxfilelen, fileFullPath);
            FileInfo file = new FileInfo(fileFullPath);
            if (!Directory.Exists(file.DirectoryName))
            {
                Directory.CreateDirectory(file.DirectoryName);
            }

            StreamWriter sw = new StreamWriter(newfileFullPath, true, System.Text.Encoding.GetEncoding("GB2312"));
            sw.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "]		" + content);
            sw.Close();
        }

        private static string GetfileFullPath(int maxfilelen, string fileFullPath)
        {
            FileInfo file = new FileInfo(fileFullPath);
            if (!file.Exists)
            {
                return fileFullPath;
            }

            if (file.Length > maxfilelen * 1024)
            {
                int i = fileFullPath.LastIndexOf('_') + 1;
                int index = int.Parse(fileFullPath.Substring(i, 1));
                fileFullPath = fileFullPath.Substring(0, i) + (index + 1).ToString() + ".log";
                return GetfileFullPath(maxfilelen, fileFullPath);
            }
            return fileFullPath;
        }

        /// <summary>
        /// 在文件末尾写一行字符串,如果文件名为 Null 或 "" ，则不作任何处理
        /// </summary>
        /// <param name="logFileName"></param>
        /// <param name="LogString"></param>
        public static void writeFile(string logFileName, string LogString, string encoding)
        {
            FileInfo f = new FileInfo(logFileName);
            // 如果文件所在的文件夹不存在则创建文件夹
            if (!Directory.Exists(f.DirectoryName)) Directory.CreateDirectory(f.DirectoryName);
            StreamWriter sWriter = new StreamWriter(logFileName, true, System.Text.Encoding.GetEncoding(encoding));
            try
            {
                sWriter.Write(LogString);
            }
            catch (Exception exc)
            {
                throw new Exception(exc.ToString());
            }
            finally
            {
                sWriter.Flush();
                sWriter.Close();
            }
        }

        /// <summary>
        /// 在文件末尾写一行字符串,如果文件名为 Null 或 "" ，则不作任何处理
        /// </summary>
        /// <param name="logFileName"></param>
        /// <param name="LogString"></param>
        public static void writeFile(string logFileName, string LogString)
        {
            writeFile(logFileName, LogString, "gb2312");
        }

        /// <summary>
        /// 覆盖写文件
        /// </summary>
        /// <param name="logFileName"></param>
        /// <param name="LogString"></param>
        public static void OverWriteFile(string logFileName, string LogString)
        {
            if ((logFileName != null) && (logFileName.Trim() != ""))
            {
                File.Delete(logFileName);
                FileStream fs = new FileStream(logFileName, FileMode.OpenOrCreate, FileAccess.Write);
                StreamWriter m_streamWriter = new StreamWriter(fs);
                m_streamWriter.BaseStream.Seek(0, SeekOrigin.Begin);
                m_streamWriter.WriteLine(LogString + "\r\n");
                m_streamWriter.Flush();
                m_streamWriter.Close();
                fs.Close();
            }
        }
        /// <summary>
        /// 覆写GB2312文件
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="FileContent"></param>
        public static void OverWriteGB2312File(string FileName, string FileContent)
        {
            OverWriteEncodeFile(FileName, FileContent, "GB2312");
        }

        /// <summary>
        /// 覆盖文件 可制定编码
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="FileContent"></param>
        /// <param name="encoding"></param>
        public static void OverWriteEncodeFile(string FileName, string FileContent, string encoding)
        {
            FileInfo f = new FileInfo(FileName);
            // 如果文件所在的文件夹不存在则创建文件夹
            if (!Directory.Exists(f.DirectoryName)) Directory.CreateDirectory(f.DirectoryName);
            StreamWriter sWriter = new StreamWriter(FileName, false, System.Text.Encoding.GetEncoding(encoding));
            try
            {
                sWriter.Write(FileContent);
            }
            catch (Exception exc)
            {
                throw new Exception(exc.ToString());
            }
            finally
            {
                sWriter.Flush();
                sWriter.Close();
            }
        }

        /// <summary>
        /// 读取文件
        /// </summary>
        /// <param name="logFileName"></param>
        /// <returns></returns>
        public static string readFile(string logFileName)
        {
            string temp = "";
            if (File.Exists(logFileName))
            {
                FileStream fs = new FileStream(logFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                StreamReader reader = new StreamReader(fs);
                temp = reader.ReadToEnd();
                reader.Close();
            }
            return temp;
        }

        /// <summary>
        /// 读取文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string readFile(string fileName, string encoding)
        {
            string temp = "";
            if (File.Exists(fileName))
            {
                FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                StreamReader reader = new StreamReader(fs, System.Text.Encoding.GetEncoding(encoding));
                temp = reader.ReadToEnd();
                reader.Close();
            }
            return temp;
        }

        /// <summary>
        /// 用GB2312编码读文件
        /// </summary>
        /// <param name="logFileName"></param>
        /// <returns></returns>
        public static string readGB2312File(string logFileName)
        {
            string temp = "";
            try
            {
                if (File.Exists(logFileName))
                {
                    FileStream fs = new FileStream(logFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    StreamReader reader = new StreamReader(fs, System.Text.Encoding.GetEncoding("GB2312"));
                    temp = reader.ReadToEnd();
                    reader.Close();
                }
            }
            catch
            {
            }
            return temp;
        }
        /// <summary>
        /// 流的形式读文件
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static string readIoStream(Stream stream)
        {
            if (stream.Length > 0)
            {
                StreamReader reader = new StreamReader(stream);
                return reader.ReadToEnd();
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 文件移动
        /// </summary>
        /// <param name="sourceFileName"></param>
        /// <param name="destFileName"></param>
        public static void Move(string sourceFileName, string destFileName)
        {
            if (File.Exists(sourceFileName))
            {
                FileInfo f = new FileInfo(destFileName);
                // 如果文件所在的文件夹不存在则创建文件夹
                if (!Directory.Exists(f.DirectoryName)) Directory.CreateDirectory(f.DirectoryName);
                if (File.Exists(destFileName)) File.Delete(destFileName);
                File.Move(sourceFileName, destFileName);
            }
        }
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filename"></param>
        public static void Delete(string filename)
        {
            try
            {
                if (File.Exists(filename))
                {
                    File.Delete(filename);
                }
            }
            catch
            {
            }
        }
        public bool IsEmpty(string filename)
        {

            return System.IO.Directory.GetFiles(filename, "*.*", SearchOption.AllDirectories).Length == 0
                   && System.IO.Directory.GetDirectories(filename, "*.*", SearchOption.AllDirectories).Length == 0;
        }
    }
}
